package org.test.java;

import static org.test.java.ShuaTa.httpRequestWithLogFile;
import static org.test.java.ShuaTa.print;
import static org.test.java.ShuaTa.sleepTime;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Properties;

@SuppressWarnings("rawtypes")
public class RankCompete implements Runnable {

	private String _sid;
	Properties props;
	private static String logFile = "RankCompete.log";

	public RankCompete(String _sid, Properties props) {
		this._sid = _sid;
		this.props = props;
		if (props.containsKey("rankCompeteLogFile")) {
			logFile = props.getProperty("rankCompeteLogFile");
		}
		sleepTime = 60;
	}

	@Override
	public void run() {
		int temp = 0;
		while (true) {
			try {
				try {
					if (temp >= 1)
						Thread.sleep(sleepTime * 60 * 1000);
					temp++;
				} catch (InterruptedException e1) {
					e1.printStackTrace();
					log(e1.getMessage());
				}

				Map result = httpRequestWithLogFile(_sid, "arena.php",
						"GetRankCompetitors", "", logFile);
				if (getInt(result, "status") != 1) {
					continue;
				}
				Map data = (Map) result.get("data");
				int competeRank = Integer.MAX_VALUE;
				for(Object obj : (List)data.get("Competitors")){
					Map competitor = (Map)obj;
					competeRank = Math.min(competeRank, getInt(competitor,"Rank"));
				}
				result = httpRequestWithLogFile(_sid, "arena.php",
						"RankFight", "CompetitorRank="+competeRank, logFile);
				log(result.toString());
			} catch (IOException e) {
				log(e.getMessage());
			}
		}
	}

	private int getInt(Map map, String key) {
		return (Double.valueOf(map.get(key).toString())).intValue();
	}

	private void log(String result) {
		try {
			print(logFile, result);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}
}
